package com.dmbjz.oauth2.controller;


import cn.hutool.core.bean.BeanUtil;
import com.dmbjz.common.model.domain.ResultInfo;
import com.dmbjz.common.model.domain.SignInidentity;
import com.dmbjz.common.model.vo.SingInDinerInfo;
import com.dmbjz.common.utils.ResultInfoUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


/*用户中心*/
@RestController
public class UserController {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisTokenStore redisTokenStore;

    @GetMapping("user/me")
    public ResultInfo getCurrentUser( Authentication authentication ){

        SignInidentity principal = (SignInidentity) authentication.getPrincipal();//获取登录后用户的信息并设置
        SingInDinerInfo dinerInfo = new SingInDinerInfo();//转为前端可用的视图对象
        BeanUtil.copyProperties(principal,dinerInfo);
        return ResultInfoUtil.buildSuccess(request.getServletPath(),dinerInfo);

    }

    /*安全退出*/
    @GetMapping("user/logout")
    public ResultInfo logout(String access_token,String authorization){

        if(StringUtils.isBlank(access_token)){
            access_token = authorization;

        }
        if(StringUtils.isBlank(access_token)){
            return ResultInfoUtil.buildSuccess(request.getServletPath(),"退出成功!");
        }
        /*判断 bearar token是否为空*/
        if( access_token.toLowerCase().contains("bearer".toLowerCase()) ) {
            access_token = access_token.toLowerCase().replace("bearer", "");
        }
        /*清空Redis信息*/
        OAuth2AccessToken oAuth2AccessToken = redisTokenStore.readAccessToken(access_token);
        if( oAuth2AccessToken!=null ){
            redisTokenStore.removeAccessToken(oAuth2AccessToken);
            OAuth2RefreshToken refreshToken = oAuth2AccessToken.getRefreshToken();
            redisTokenStore.removeRefreshToken(refreshToken);
        }

        return ResultInfoUtil.buildSuccess(request.getServletPath(),"退出成功!");

    }



}
